import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @ClassName StaticResourceUtil
 * @Deseription 静态资源工具类
 * @Author fx
 * @Date 2021/1/10 0010 16:27
 * @Version 1.0
 **/
public class StaticResourceUtil {

    /**
     * @Author fx
     * @Description 获取静态资源绝对路径
     * @ClassName StaticResourceUtil
     * @Date 16:29 2021/1/10 0010
     * @Param
     * @return
     **/
    public static String getAbsolutePath(String path){
        String absolutePath = StaticResourceUtil.class.getResource("/").getPath()+path;
        return absolutePath.replace("\\\\","/");
    }

    /**
     * @Author fx
     * @Description 读取静态资源文件输入流，通过输出流输出
     * @ClassName StaticResourceUtil
     * @Date 16:34 2021/1/10 0010
     * @Param
     * @return
     **/
    public static void outputStaticResource(InputStream inputStream, OutputStream outputStream) throws IOException {
        int count = 0;
        while(count == 0){
            count = inputStream.available();
        }

        int resoureSize = count;
        //输出请求头
        outputStream.write(HttpProtocolUtil.getHead200(resoureSize).getBytes());
        //已读取的内容长度
        int written = 0;
        //设置每次读取内容长度的大小
        int byteSize = 1024;
        byte[] bytes = new byte[byteSize];
        //当读取的内容长度小于输入流内存的总长度，一直循环读取
        while (written < resoureSize){
            //当读取的内容长度 + 每次读取设置的长度大小  > 总长度 ，代表此次读取的长度不足设置的长度的大小，需重新指定读取长度
            if(written + byteSize > resoureSize){
                //剩余内容的长度
                byteSize = (int)(resoureSize - written);
                bytes = new byte[byteSize];
            }

            inputStream.read(bytes);
            outputStream.write(bytes);

            outputStream.flush();
            written += byteSize;
        }
    }
}
